1361B - Johnny and Grandmaster - CodeForces Solution


greedy implementation math sortings *1900

Please click on ads to support us..

Python Code:

import sys
input = sys.stdin.readline
for _ in range(int(input())):
    n, p = map(int, input().split());s = list(map(int, input().split()));s.sort(reverse=True)
    if p == 1:print(n % 2);continue
    c = -1;ci = 0
    for i, si in enumerate(s):
        if c == -1:c = si;ls = si;f = 1;ci = i
        else:
            d = ls - si
            if d > 20:break
            elif d:f *= p ** d
            ls = si;f -= 1
            if f > n:break
            if f == 0:c = -1
    if c != -1:
        ans = pow(p, c, 1000000007)
        for si in s[ci+1:]:ans -= pow(p, si, 1000000007)
        ans %= 1000000007;ans += 1000000007
    else:ans = 0
    print(ans % 1000000007)

C++ Code:

#include<iostream>
#include<algorithm>
using namespace std;

const int N = 1000000;
long long mod = 1000000007;

long long ksm(long long p, long long x) {
	long long res = 1;
	while(x) {
		if(x & 1) {
			res = (res * p) % mod;
		}
		p = (p * p) % mod;
		x >>= 1;
	}
	return res;
}

struct asd{
	int v, c;
}e[N];

int main() {
	int t, i, n, p, a[N];
	bool flag;
	int tar, k, l;
	long long res;
	for(cin >> t; t; t--) {
		cin >> n >> p;
		flag = true;
		l = 0;
		for(i = 0; i < n; i++) cin >> a[i];
		if(p == 1) {
			cout << n % 2 << endl;
			continue;
		}
		sort(a, a + n);
		tar = a[n - 1];
		for(i = n - 2; i > -1; i--) {
			k = a[i];
			while(l && k == e[l - 1].v && e[l - 1].c == p - 1) {
				l--;
				k++;
			}
			if(k == tar) {
				if(i == 0) {
					cout << 0 << endl;
					flag = false;
					l = 0;
					break;
				}
				i--;
				tar = a[i];
			} else if(l && k == e[l - 1].v) {
				e[l - 1].c++;
			} else {
				e[l].c = 1;
				e[l].v = k;
				l++;
			}
		}
		res = ksm(p, tar);
		for(i = 0; i < l; i++) {
			res -= e[i].c * ksm(p, e[i].v);
			res %= mod;
		}
		res = (res + mod) % mod;
		if(flag) cout << res << endl;
	}
	return 0;
}


Comments

Submit
0 Comments
More Questions

727A - Transformation from A to B
822B - Crossword solving
1623A - Robot Cleaner
884B - Japanese Crosswords Strike Back
862B - Mahmoud and Ehab and the bipartiteness
429A - Xor-tree
1675C - Detective Task
950A - Left-handers Right-handers and Ambidexters
672B - Different is Good
1C - Ancient Berland Circus
721A - One-dimensional Japanese Crossword
1715B - Beautiful Array
60B - Serial Time
453A - Little Pony and Expected Maximum
1715A - Crossmarket
1715C - Monoblock
1512C - A-B Palindrome
1679B - Stone Age Problem
402A - Nuts
792A - New Bus Route
221A - Little Elephant and Function
492C - Vanya and Exams
1369B - AccurateLee
892B - Wrath
999A - Mishka and Contest
727C - Guess the Array
1625C - Road Optimization
1715D - 2+ doors
267A - Subtractions
1582A - Luntik and Concerts